#include <QtGui>
#include "asowindow.h"

AsoWindow::AsoWindow(QWidget* parent)
    : QMainWindow(parent), window(new Ui::AsoWindowClass)
{
    window->setupUi(this);
    initWindowValues();
    connectSignals();
    createActions();
}

AsoWindow::~AsoWindow()
{
    delete window;
    delete pluginParameters;
    delete sequenceView;
}

void AsoWindow::initWindowValues()
{
    pluginParameters = 0;
    sequenceView = 0;
    outputDir = "../outputs/";
    pluginFile = "";
    sequenceFile = "";
    dataBaseFile = "";
    window->resetButton->setEnabled(false);
    window->printButton->setEnabled(false);
    window->btnViewSeq->setEnabled(false);
    window->btnViewDataBase->setEnabled(false);
}

void AsoWindow::reloadPlugin()
{
    pluginFile.clear();
    window->plgName->clear();
}

void AsoWindow::connectSignals()
{
    connect(window->seqButton, SIGNAL(clicked()), this, SLOT(onLoadSequencePressed()));
    connect(window->dbButton, SIGNAL(clicked()), this, SLOT(onLoadDataBasePressed()));
    connect(window->plgButton, SIGNAL(clicked()), this, SLOT(onLoadPluginPressed()));
    connect(window->runButton, SIGNAL(clicked()), this, SLOT(onRunProgram()));
    connect(window->resetButton, SIGNAL(clicked()), this, SLOT(onResetPressed()));
    connect(window->printButton, SIGNAL(clicked()), this, SLOT(onPrintPressed()));
    connect(window->btnViewSeq, SIGNAL(clicked()), this, SLOT(onViewSeqPressed()));
}

void AsoWindow::createActions()
{
    connect(window->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(window->actionAbout, SIGNAL(triggered()), this, SLOT(onAboutClicked()));
}




//Slots

void AsoWindow::onAboutClicked()

{
    QMessageBox::information(this, tr("About ASO"),
                             tr("ASO: Antiviral Sequencer Optimizer.\n\n"
                                "Copyright 2010 Fu.De.P.A.N.\n\n"
                                "Report Bugs to: aso@fudepan.org"));
}

void AsoWindow::onLoadDataBasePressed()
{
    window->dbFile->clear();
    dataBaseFile = QFileDialog::getOpenFileName(this, tr("Data Base File"), QDir::currentPath());
    QFileInfo dbFile(dataBaseFile);

    if (dbFile.isReadable())
    {
        if (dbFile.suffix() == "xml")
        {
            window->dbFile->setText(dbFile.filePath());
        }
        else
        {
            QMessageBox::critical(this, "Error", "Incorrect file extension.\nFile must have xml extenstion.");
        }
    }
    else
    {
        QMessageBox::critical(this, "Error", "Cannot open the file");
    }
}

void AsoWindow::onLoadPluginPressed()
{
    reloadPlugin();
    window->plgFile->clear();
    pluginFile = QFileDialog::getOpenFileName(this, tr("Plugin File"), QDir::currentPath());
    QFileInfo plgFile(pluginFile);

    if (pluginParameters)
    {
        delete pluginParameters;
        pluginParameters = 0;
    }

    if (!pluginFile.isNull())
    {
        if (plgFile.suffix() == "so")
        {
            try
            {
                window->plgFile->setText(plgFile.filePath());
                pluginAdmin.load_plugin(qtTostdString(pluginFile));
                window->plgName->setText(stdToqtString(pluginAdmin.get_name()));
                ParameterList listparams;
                pluginAdmin.get_params(listparams);

                pluginParameters = new ParametersWidget;
                pluginParameters->loadParameters(listparams);
                window->pluginLayout->addWidget(pluginParameters);
            }
            catch (const PluginError& e)
            {
                QMessageBox::critical(this, "Error", "Cannot load the plugin");
            }
        }
        else
        {
            QMessageBox::critical(this, "Error", "Incorrect file extension.\nFile must have so extension.");
        }
    }
    else
    {
        QMessageBox::critical(this, "Error", "Cannot open the file");
    }
}

void AsoWindow::onLoadSequencePressed()
{
    window->seqFile->clear();
    window->btnViewSeq->setEnabled(false);
    sequenceFile = QFileDialog::getOpenFileName(this, tr("Sequence File"), QDir::currentPath());
    QFileInfo seqFile(sequenceFile);

    if (sequenceView)
    {
        delete sequenceView;
        sequenceView = 0;
    }

    if (seqFile.isReadable())
    {
        if (seqFile.suffix() == "txt")
        {
            window->seqFile->setText(seqFile.filePath());
            window->btnViewSeq->setEnabled(true);
            sequenceView = new SequenceViewer;
            sequenceView->loadSequenceView(sequenceFile);

        }
        else
        {
            QMessageBox::critical(this, "Error", "Incorrect file extension.\nFile must have txt extension.");
        }
    }
    else
    {
        QMessageBox::critical(this, "Error", "Cannot open the file");
    }
}

void AsoWindow::onViewSeqPressed()
{
    sequenceView->showSequenceWindow();
}

void AsoWindow::onRunProgram()
{
    if (!sequenceFile.isEmpty())
    {
        if (!dataBaseFile.isEmpty())
        {
            if (!pluginFile.isEmpty())
            {
                if (!window->outfileName->text().isEmpty())
                {
                    runAso(sequenceFile, dataBaseFile, pluginAdmin,
                           window->rankVal->value(), window->obsText->toPlainText(),
                           window->outfileName->text());

                    window->resetButton->setEnabled(true);
                    window->runButton->setEnabled(false);
                    window->printButton->setEnabled(true);
                    showOutput(window->outfileName->text());
                }
                else
                {
                    QMessageBox::critical(this, "Error", tr("Ouput file needed."));
                }
            }
            else
            {
                QMessageBox::critical(this, "Error", tr("Plugin file needed."));
            }
        }
        else
        {
            QMessageBox::critical(this, "Error", tr("Data Base file needed."));
        }
    }
    else
    {
        QMessageBox::critical(this, "Error", tr("Sequence file needed."));

    }
}

void AsoWindow::onResetPressed()
{
    if (QMessageBox::question(this, "Reset parameters", tr("Do you want to clean all the parameters?"),
                              tr("&No"), tr("&Yes"),
                              QString::null, 0, 1))
    {

        window->seqFile->clear();
        window->dbFile->clear();
        window->obsText->clear();
        window->plgFile->clear();
        window->plgName->clear();
        window->outfileName->clear();
        window->outputText->clear();
        window->runButton->setEnabled(true);
        delete pluginParameters;
        initWindowValues();
    }
}

void AsoWindow::onPrintPressed()
{
    QTextDocument* documentToPrint = window->outputText->document();
    QPrinter aPrinter;

    QPrintDialog* printDialog = new QPrintDialog(&aPrinter, this);
    if (printDialog->exec() == QDialog::Accepted)
    {
        documentToPrint->print(&aPrinter);
    }
}

void AsoWindow::showOutput(QString fileName)
{
    fileName += ".trp";
    outputDir += fileName;
    QFile outFile(outputDir);
    if (outFile.open(QIODevice::ReadOnly))
        window->outputText->setPlainText(outFile.readAll());
}

